package cn.sangyy.gift.datasys.mqlistenser;

import cn.sangyy.gift.datasys.dto.CanalSynDto;
import cn.sangyy.gift.doc.SpuGiftDoc;
import cn.sangyy.gift.repository.SpuGiftRepository;
import com.alibaba.fastjson2.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "example",selectorExpression="*",consumerGroup = "service-search-consumer")
public class GiftOnSaleOrOffSaleDataSysListener implements RocketMQListener<MessageExt> {

    @Autowired
    private SpuGiftRepository repository;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        log.info("接收到消息：{}", msg);
        CanalSynDto canalSynDto = JSONObject.parseObject(msg, CanalSynDto.class);
        List<JSONObject> dtoData = canalSynDto.getData();
        List<SpuGiftDoc> onSaleDetailDocs = dtoData.stream().
                map(d -> d.toJavaObject(SpuGiftDoc.class)).collect(Collectors.toList());
        //上架   下架
        String type = canalSynDto.getType();
        if(type.equals("DELETE")){
            //下架
            onSaleDetailDocs.forEach(d -> {
                repository.deleteById(d.getId());
            });
        }else {
            //上架
            repository.saveAll(onSaleDetailDocs);
        }
    }

}